#include "CannonMunition.h"
#include <math.h>

#define PI 3.14
static const int DAMAGE = 2;

CannonMunition::CannonMunition(Map *m)
{
	map = m;
	damage = DAMAGE;
	width = 0.7;	// Z
	lenght = 1;		// X
	height = 0.6;	// Y
	sizeCannon = 0.25;
	lenghtCannon = 0.7;
	elevation = 0;
	oldX = 0;
	oldZ = 0;
	angle = 0;
	angleAnimation = 0;
	quad = gluNewQuadric();
	loadImage();
}

void CannonMunition::loadImage()
{
	Image* image = loadBMP("textures\\textureAluNumber.bmp");
	textureCannon = loadTexture(image);
	delete image;
}

void CannonMunition::setAngle(GLfloat a)
{
	if(!animated)
	{
		angle = a;
		angleAnimation = angle;
	}
	else
		angle = a;
}

void CannonMunition::display()
{
	if(animated)
	{
		for (int i=0; i!=2; ++i)
		{
			glPushMatrix();
				glTranslatef(0.0, elevation, 0.0);
				glTranslatef(x, 0, z);
				//glRotatef(180*angleAnimation/PI, 0, 1, 0);
				glRotatef(angleAnimation, 0, 1, 0);

				glTranslatef(pow(-1.0, i)*lenght/4, 0.0, (width/2 + lenghtCannon/6));
				glPushMatrix();
					glBindTexture(GL_TEXTURE_2D, textureCannon);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
					glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
					glColor3f(1.0f, 1.0f, 1.0f);
					gluSphere(quad, sizeCannon/4, 30, 5);
				glPopMatrix();
			glPopMatrix();
		}
	}
}

void CannonMunition::animate()
{
	if(animated)
	{
		oldX += sin(PI*angleAnimation/180);
		oldZ += cos(PI*angleAnimation/180);

		int idEnnemy = map->move(myX + sin(PI*angleAnimation/180), y, myZ + cos(PI*angleAnimation/180));
		if (!idEnnemy)
		{
			x = oldX;
			z = oldZ;
			y = elevation;
			myX += sin(PI*angleAnimation/180);
			myZ += cos(PI*angleAnimation/180);
		}
		else if(idEnnemy < 0)
		{
			reset();
		}
		else
		{
			collisionID = idEnnemy;
			crash = true;
			reset();
		}
	}
}

void CannonMunition::reset()
{
	oldX = 0;
	oldZ = 0;
	x = 0;
	z = 0;
	myX = xPos;
	myY = yPos;
	myZ = zPos;
	angleAnimation = angle;
	animated = false;
}

CannonMunition::~CannonMunition(void)
{
	gluDeleteQuadric(quad);
}
